package com.smh;

import org.junit.jupiter.api.Test;

import java.util.Iterator;

/**
 * @author shiminghui
 * @date 2025/2/15 15:28
 * @description: TODO
 */
public class _016_栈_链表 {


    @Test
    public void test1() {
        LinkedListStack<Integer> stack = new LinkedListStack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        for (Integer i : stack) {
            System.out.println(i);
        }
    }


    public static class LinkedListStack<T> implements Iterable<T> {

        private final LinkedListNode<T> head = new LinkedListNode<>();
        private int size;
        private int capacity;

        public LinkedListStack(int capacity) {
            this.capacity = capacity;
        }

        public LinkedListStack() {
            this.capacity = 10;
        }

        public boolean push(T data) {
            if (size >= capacity) {
                return false;
            }
            LinkedListNode<T> node = new LinkedListNode<>(data);
            node.next = head.next;
            head.next = node;
            size++;
            return true;
        }

        public T pop() {
            if (size == 0) {
                return null;
            }
            LinkedListNode<T> node = head.next;
            head.next = node.next;
            size--;
            return node.data;
        }

        public T peek() {
            if (size == 0) {
                return null;
            }
            return head.next.data;
        }

        public boolean isEmpty() {
            return size == 0;
        }

        public boolean isFull() {
            return size == capacity;
        }

        @Override
        public Iterator<T> iterator() {
            return new Iterator<T>() {
                LinkedListNode<T> node = head;

                @Override
                public boolean hasNext() {
                    if (node.next == null)
                        return false;
                    return true;
                }

                @Override
                public T next() {
                    LinkedListNode<T> next = node.next;
                    node = next;
                    return next.data;
                }
            };
        }


        private static class LinkedListNode<T> {
            private T data;
            private LinkedListNode<T> next;

            public LinkedListNode(T data, LinkedListNode<T> next) {
                this.data = data;
                this.next = next;
            }

            public LinkedListNode(T data) {
                this.data = data;
            }

            public LinkedListNode() {
            }
        }
    }


}
